package cn.bqjr.eily.web.utils;

import cn.bqjr.eily.mybatis.spring.boot.entity.PageInfoVO;
import cn.bqjr.eily.mybatis.spring.boot.utils.PagingUtils;
import cn.bqjr.eily.web.entity.BaseResponseVO;
import cn.bqjr.eily.web.entity.PagingResponseVO;
import cn.bqjr.eily.web.exception.ErrorInfo;
import com.github.pagehelper.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletRequest;

public class RUtils {
    /**
     * 获取分页返回结果
     *
     * @param pageList
     * @return
     */
    public static BaseResponseVO pagingResponse(Page pageList) {
        return new PagingResponseVO(pageList).success();
    }

    /**
     * 获取返回空结果
     * @return
     */
    public static BaseResponseVO baseResponse() {
        return new BaseResponseVO();
    }

    /**
     * 返回错误信息
     * @param errorInfo
     * @return
     */
    public static ResponseEntity error(ErrorInfo errorInfo) {
        BaseResponseVO resp = new BaseResponseVO().setHasError(true).setErrors(errorInfo);
        return new ResponseEntity(resp, HttpStatus.valueOf(errorInfo.getHttpStatus()));
    }

    public static BaseResponseVO ok() {
        return baseResponse().success();
    }

    public static BaseResponseVO ok(Object obj) {
        return ok().setResultData(obj);
    }

    /**
     * 返回成功信息，并根据request自动判断是否需要返回分页结果
     * @param request
     * @param obj
     * @return
     */
    public static BaseResponseVO ok(HttpServletRequest request, Object obj) {
        if (PagingUtils.isPagingRequest(request)) {
            return ok(PagingUtils.getRequestPageInfo(request), obj);
        }
        return ok(obj);
    }

    public static BaseResponseVO ok(PageInfoVO page, Object obj) {
        if (PagingUtils.validPage(page) && obj instanceof Page) {
            return pagingResponse((Page) obj);
        } else {
            return ok(obj);
        }
    }
}
